package notInLeetcode;

import util.ListNode;

/**
 * 给定一个奇数位升序，偶数位降序的链表，将其重新排序。
 * <p>
 * 输入: 1->8->3->6->5->4->7->2->NULL
 * 输出: 1->2->3->4->5->6->7->8->NULL
 */
public class ListSort {
    public ListNode sort(ListNode root) {
        if (root == null || root.next == null) return root;
        //1.构造偶数链表
        ListNode oRoot = root.next;
        ListNode oCur = oRoot;
        ListNode jCur = root;
        while (oCur != null && oCur.next != null) {
            jCur.next = oCur.next;
            jCur = jCur.next;
            oCur.next = jCur.next;
            oCur = oCur.next;
        }

        //2.反转偶数链表
        ListNode reverseNode = reverse(oRoot);
        //3.合并两个排序链表
        return merge(root, reverseNode);
    }

    public ListNode reverse(ListNode root) {
        ListNode pre = null, cur = root;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) return null;
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 == null ? l2 : l1;
        return dummy.next;
    }

    public static void main(String[] args) {
        ListSort listSort = new ListSort();
        ListNode sort = listSort.sort(ListNode.build());
        System.out.println(sort);
    }
}
